<template>
  <div class="user-index">
    <a-card>
      <InputGroup @search="Search" @reset="Reset">
        <a-form
          :model="formData"
          :wrapper-col="{ style: { width: '150px' } }"
          layout="inline"
        >
          <a-form-item label="用户名称">
            <a-input v-model:value="formData.username" allow-clear></a-input>
          </a-form-item>
          <a-form-item label="电话">
            <a-input v-model:value="formData.phone" allow-clear></a-input>
          </a-form-item>
          <a-form-item label="状态">
            <a-select ref="select" v-model:value="formData.status">
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="0">停用</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </InputGroup>

      <a-flex justify="flex-end" style="margin-bottom: 16px">
        <a-space>
          <a-button type="primary" @click="Add">
            <icon type="PlusOutlined" />
            新增用户
          </a-button>
        </a-space>
      </a-flex>

      <Table
        ref="table"
        :config="tableConfig"
        @edit="Edit"
        @delete="Delete"
        @role="Role"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.title === '状态'">
            <a-switch
              v-model:checked="record.status"
              :checkedValue="1"
              :unCheckedValue="0"
              @change="Switch(record)"
            />
          </template>
        </template>
      </Table>

      <Dialog :config="dialogConfig" @submit="Submit" @cancel="Cancel">
        <a-spin :spinning="dialogLoading">
          <a-form
            :model="dialogData"
            :disabled="dialogFormDisabled"
            :labelCol="{ span: 4 }"
            :wrapperCol="{ span: 20 }"
          >
            <a-form-item label="用户名称">
              <a-input v-model:value="dialogData.username" />
            </a-form-item>
            <a-form-item v-if="!isEdit" label="用户密码">
              <a-input v-model:value="dialogData.password" />
            </a-form-item>
            <a-form-item label="电话">
              <a-input v-model:value="dialogData.phone" />
            </a-form-item>
            <a-form-item label="微信">
              <a-input v-model:value="dialogData.wechat" />
            </a-form-item>
            <a-form-item label="email">
              <a-input v-model:value="dialogData.email" />
            </a-form-item>

            <a-form-item label="状态">
              <a-radio-group v-model:value="dialogData.status">
                <a-radio :value="1">正常</a-radio>
                <a-radio :value="0">停用</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </a-spin>
      </Dialog>

      <Dialog
        :config="authRoleDialogConfig"
        @submit="subRoles"
        @cancel="Cancel"
      >
        <a-spin :spinning="dialogLoading">
          <a-form-item label="角色列表">
            <a-select
              v-model:value="userRoles"
              mode="tags"
              style="width: 100%"
              placeholder="请选择角色"
              :field-names="{
                label: 'roleName',
                value: 'id',
              }"
              :options="rolesOptions"
            >
            </a-select>
          </a-form-item>
        </a-spin>
      </Dialog>
    </a-card>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import InputGroup from "@/components/InputGroup/index.vue";
import Dialog from "@components/Dialog/index.vue";
import icon from "@utils/icon";
import { message, Modal } from "ant-design-vue";
import {
  getUserList,
  getUserById,
  userDelete,
  userChangeStatus,
  userAdd,
  userAddRole,
} from "@api/system/user.js";
import { getRoleList } from "@api/system/role.js";
import { createVNode, ref } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";

// 表单是否禁用
const dialogFormDisabled = ref(true);
// 弹窗加载数据loading
const dialogLoading = ref(false);
// 是否编辑
const isEdit = ref(false);
// 表格实例
const table = ref(null);
// 搜索数据
const formData = ref({
  username: "",
  phone: "",
  status: "",
});
// 角色列表
const rolesOptions = ref([]);
// 用户Id,提交分配角色列表使用
const userId = ref();
// 用户已有角色列表
const userRoles = ref([]);

// 新增、查看、修改弹窗表单数据
let dialogData = ref({
  username: "",
  password: "",
  phone: "",
  wechat: "",
  email: "",
  status: 1,
  // roles: [],
});
// 表格配置
const tableConfig = reactive({
  url: getUserList,
  columns: [
    {
      key: "username",
      title: "用户名称",
      dataIndex: "username",
      align: "center",
    },
    {
      key: "phone",
      title: "电话",
      dataIndex: "phone",
      align: "center",
    },
    {
      key: "wechat",
      title: "微信",
      dataIndex: "wechat",
      align: "center",
    },
    {
      key: "email",
      title: "email",
      dataIndex: "email",
      align: "center",
    },
    {
      key: "status",
      title: "状态",
      dataIndex: "status",
      align: "center",
    },
    {
      title: "操作",
      align: "center",
      width: "200px",
    },
  ],
  params: {},
  table: {
    size: "middle",
    bordered: true,
  },
  isPagination: true,
  dataPath: "data.records",
  buttons: {
    view: [],
    edit: ["system:user:update"],
    add: [],
    delete: ["system:user:delete"],
    role: ["system:user:role"],
  },
});
// 新增、查看、修改弹窗配置
const dialogConfig = reactive({
  open: false,
  title: "添加用户",
  width: "30%",
  okText: "确定",
  cancelText: "取消",
  confirmLoading: false,
  destroyOnClose: true,
});

const authRoleDialogConfig = reactive({
  open: false,
  title: "分配角色",
  width: "30%",
  okText: "确定",
  cancelText: "取消",
  confirmLoading: false,
  destroyOnClose: true,
});

const Search = () => {
  tableConfig.params = formData.value;
  table.value.loadData();
};
const Reset = () => {
  formData.value = {};
  tableConfig.params = formData.value;
  table.value.loadData();
};

const getSelectOptions = async () => {
  const response = await getRoleList({});
  if (response.code === 200) {
    rolesOptions.value = response.data;
  } else {
    message.error("获取角色列表失败，" + response.message);
  }
};

// 表格查看、编辑、删除
// const View = async (record) => {
//   dialogConfig.open = true;
//   dialogConfig.title = "查看用户";
//   dialogFormDisabled.value = true;
//   const response = await getUserById(record.id);
//   if (response.code === 200) {
//     dialogData.value = response.monitor;
//   } else {
//     message.error("获取角色信息失败，" + response.message);
//   }
// };
const Add = async () => {
  isEdit.value = false;
  dialogConfig.open = true;
  dialogFormDisabled.value = false;
  dialogConfig.title = "新增用户";
};
const Edit = async (record) => {
  dialogLoading.value = true;
  isEdit.value = true;
  dialogConfig.open = true;
  dialogConfig.title = "编辑用户";
  dialogFormDisabled.value = false;
  const response = await getUserById(record.id);
  if (response.code === 200) {
    dialogData.value = response.data;
  } else {
    message.error("获取角色信息失败，" + response.message);
  }
  dialogLoading.value = false;
};
const Delete = async (record) => {
  // 弹窗确认删除
  Modal.confirm({
    title: "删除用户",
    icon: createVNode(ExclamationCircleOutlined),
    content: "是否确认删除该用户？",
    centered: true,
    async onOk() {
      try {
        const response = await userDelete([record.id]);
        if (response.code === 200) {
          message.success("删除成功！");
          table.value.loadData();
        } else {
          message.error("删除失败，" + response.message);
        }
      } catch {
        return console.log("errors!");
      }
    },
    onCancel() {},
  });
};

// 分配角色
const Role = async (record) => {
  dialogLoading.value = true;
  authRoleDialogConfig.open = true;
  userId.value = record.id;
  await getSelectOptions();
  const response = await getUserById(record.id);
  if (response.code === 200) {
    userRoles.value = response.data.roles.map((item) => {
      return item.id;
    });
  } else {
    message.error("获取角色信息失败，" + response.message);
  }
  dialogLoading.value = false;
};
// 表格项状态切换
const Switch = async (record) => {
  const response = await userChangeStatus({
    id: record.id,
  });
  if (response.code === 200) {
    message.success("修改状态成功！");
    table.value.loadData();
  } else {
    message.error("修改状态失败，" + response.message);
    table.value.loadData();
  }
};

// 弹窗表单提交
const Submit = async () => {
  dialogConfig.subLoading = true;
  const response = await userAdd(dialogData.value);
  if (response.code === 200) {
    message.success("操作成功！");
    dialogConfig.open = false;
    dialogData.value = {};
    table.value.loadData();
  } else {
    message.error("操作失败，" + response.message);
  }
  dialogConfig.subLoading = false;
  // try {
  //   const response = isEdit.value
  //     ? await userEdit(dialogData.value)
  //     : await userAdd(dialogData.value);
  //   if (response.code === 200) {
  //     message.success(isEdit.value ? "修改成功！" : "添加成功！");
  //     dialogConfig.open = false;
  //     dialogData.value = {
  //         username: "",
  //         phone: "",
  //             wechat: "",
  //             email: "",
  //             status: 1,
  //     };
  //     table.value.loadData();
  //   } else {
  //     message.error(
  //       (isEdit.value ? "修改失败，" : "添加失败，") + response.message,
  //     );
  //   }
  // } catch (error) {
  //   message.error("操作失败，请稍后重试。");
  // } finally {
  //   dialogConfig.subLoading = false;
  // }
};

const subRoles = async () => {
  authRoleDialogConfig.subLoading = true;
  const response = await userAddRole({
    userId: userId.value,
    roleIds: userRoles.value,
  });
  if (response.code === 200) {
    authRoleDialogConfig.subLoading = false;
    message.success("操作成功！");
    authRoleDialogConfig.open = false;
    userRoles.value = [];
    table.value.loadData();
  } else {
    message.error("操作失败，" + response.message);
    authRoleDialogConfig.subLoading = false;
  }
};

// 弹窗表单取消
const Cancel = () => {
  dialogConfig.open = false;
  authRoleDialogConfig.open = false;
  dialogData.value = {
    username: "",
    phone: "",
    wechat: "",
    email: "",
    status: 1,
  };
  userRoles.value = [];
};
</script>

<style scoped lang="scss"></style>
